package vn.egame.elockscreen.activity;

import java.util.Vector;

import vn.egame.elockscreen.ELockscreenPreferences;
import vn.egame.elockscreen.OnUnlockListener;
import vn.egame.elockscreen.R;
import vn.egame.elockscreen.homelocker.HomeKeyLocker;
import vn.egame.elockscreen.service.ScreenLockerService;
import vn.egame.elockscreen.utils.Fonts;
import vn.egame.elockscreen.viewpager.BaseFragment;
import vn.egame.elockscreen.viewpager.FragmentAdapter;
import vn.egame.elockscreen.viewpager.FragmentEmpty;
import vn.egame.elockscreen.viewpager.FragmentPin;
import vn.egame.elockscreen.viewpager.FragmentUnlock;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

@SuppressLint("NewApi")
public class LockScreenDefaultActivity extends FragmentActivity implements
		OnUnlockListener {

	private Context mContext;
	private ImageView mImgBg;
	private HomeKeyLocker mHomeKeyLocker;
	private RelativeLayout rootView;
	private Bitmap bmpBackground;
	// private FrameLayoutWithBluredBackground blurBackground;

	private boolean inResume;
	private ViewPager myPager;

	private BaseFragment fragmenttwo, fragmentOne;

	int Measuredwidth = 0;
	int Measuredheight = 0;

	public void getScreenSize() {
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		Measuredheight = displaymetrics.heightPixels;
		Measuredwidth = displaymetrics.widthPixels;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		if (!ScreenLockerService.isRunning) {

			// Calendar cal = Calendar.getInstance();
			//
			// Intent intent = new Intent(this, ScreenLockerService.class);
			// PendingIntent pintent = PendingIntent
			// .getService(this, 0, intent, 0);
			//
			// AlarmManager alarm = (AlarmManager)
			// getSystemService(Context.ALARM_SERVICE);
			// // Start every minute
			// alarm.setRepeating(AlarmManager.RTC_WAKEUP,
			// cal.getTimeInMillis(),
			// 1000, pintent);

			ScreenLockerService.startActionStart(this, null, null);

		}

		this.getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

//		ScreenLockerService.isShowLock = true;

		// startService(new Intent(this, Servicelock.class));

		// getStartType(getIntent());

		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.activity_default_lock_screen);

		mImgBg = (ImageView) findViewById(R.id.imgBg);
		// blurBackground = (FrameLayoutWithBluredBackground)
		// findViewById(R.id.blurBackground);

		if (getResources().getBoolean(R.bool.portrait_only)) {
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		}

		// rootView = (RelativeLayout) findViewById(R.id.llLockscreen);
		// lockStatusBar();

		getScreenSize();

		if (isXLargeScreen(getApplicationContext())) {
			deltaMove = 100;
		} else {
			deltaMove = 20;
		}

		deltaMoveBlur = Measuredwidth / 25 * 2;

		// WallpaperManager wallpaperManager =
		// WallpaperManager.getInstance(this);
		// Drawable wallpaperDrawable = wallpaperManager.getDrawable();
		// Bitmap wallpaperBitmap = ((BitmapDrawable) wallpaperDrawable)
		// .getBitmap();
		//
		// mImgBg.setImageBitmap(wallpaperBitmap);

		// overridePendingTransition(R.anim.trans_left_in,
		// R.anim.trans_left_out);
		// getWindow().getDecorView()

		ELockscreenPreferences.getInstance().initPreferences(
				getApplicationContext());

		Fonts.getInstance().init(getApplicationContext());

		mHomeKeyLocker = new HomeKeyLocker();
		// mHomeKeyLocker.lock(this);

		Vector<BaseFragment> fragments = new Vector<BaseFragment>();

		if (ELockscreenPreferences.getInstance().isEnablePasscode()) {
			fragmenttwo = new FragmentPin();

		} else {
			fragmenttwo = new FragmentEmpty();

		}

		fragmenttwo.setmUnlockListener(this);
		fragments.add(fragmenttwo);

		fragmentOne = new FragmentUnlock();
		fragments.add(fragmentOne);

		//
		// FragmentThree fragmenthree = new FragmentThree();
		// fragments.add(fragmenthree);

		myPager = (ViewPager) findViewById(R.id.lock_pager);
		FragmentAdapter adapter = new FragmentAdapter(
				getSupportFragmentManager(), fragments);
		myPager.setAdapter(adapter);
		myPager.setCurrentItem(1);

		myPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int arg0) {

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// Log.d("Kaii", arg0 + " " + arg1 + " " + arg2);
				if (ELockscreenPreferences.getInstance().isEnablePasscode()) {

					newPos = arg2;
					if (newPos != 0 && Math.abs(newPos - oldPos) >= deltaMove) {
						oldPos = newPos;
						float alpha = (float) Math.abs(Measuredwidth - arg2)
								/ Measuredwidth;
						((FragmentPin) fragmenttwo).setAlpha(alpha);

						((FragmentUnlock) fragmentOne).setAlpha(alpha);
					}
				}

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				//
				// Log.d("Kaii", "onPageScrollStateChanged " + arg0);
			}
		});

		((LockApplication) getApplication()).isLockScreenShowing = true;

	}

	int oldPos, newPos, deltaMove;

	int oldPosBlur, newPosBlur, deltaMoveBlur;

	private void lockStatusBar() {
		View disableStatusBarView = new View(getApplicationContext());

		WindowManager.LayoutParams handleParams = new WindowManager.LayoutParams(
				WindowManager.LayoutParams.FILL_PARENT, 30,
				// This allows the view to be displayed over the status bar
				WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
				// this is to keep button presses going to the background window
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
				// this is to enable the notification to recieve touch events
						WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
						// Draws over status bar
						WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
				PixelFormat.TRANSLUCENT);

		handleParams.gravity = Gravity.TOP;

		WindowManager winMgr = (WindowManager) getSystemService(WINDOW_SERVICE);
		winMgr.addView(disableStatusBarView, handleParams);

	}

	public static boolean isXLargeScreen(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {
		if (drawable instanceof BitmapDrawable) {
			return ((BitmapDrawable) drawable).getBitmap();
		}

		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
		drawable.draw(canvas);

		return bitmap;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// if (!inResume && ScreenLockerService.isScreenOn) {
		// Animation hyperspaceJump = AnimationUtils.loadAnimation(this,
		// R.anim.scale);
		// mImgBg.startAnimation(hyperspaceJump);
		// inResume = true;
		// }
		//
		// if (ScreenLockerService.isScreenOn) {
		// Toast.makeText(getApplicationContext(), "screen is on",
		// Toast.LENGTH_SHORT).show();
		// }

		if (Build.VERSION.SDK_INT < 19) { // 19 or above api
			View v = getWindow().getDecorView();
			v.setSystemUiVisibility(View.GONE);
		} else {
			// for lower api versions.
			View decorView = getWindow().getDecorView();
			int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
					| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
			decorView.setSystemUiVisibility(uiOptions);
		}

		super.onResume();

		// mHomeKeyLocker.lock(this);
		// ((LockApplication) getApplication()).isLockScreenShowing = true;
		onCancelUnlock();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		// mHomeKeyLocker.lock(this);

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		// if (!hasFocus) {
		// ActivityManager am = (ActivityManager)
		// getSystemService(Context.ACTIVITY_SERVICE);
		// am.moveTaskToFront(getTaskId(), ActivityManager.MOVE_TASK_WITH_HOME);
		// sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
		// }

		if (!hasFocus) {

			Log.d("Focus debug", "Lost focus !");

			Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
			sendBroadcast(closeDialog);
		}
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		// mHomeKeyLocker.unlock();
		((LockApplication) getApplication()).isLockScreenShowing = false;
//		ScreenLockerService.isShowLock = false;
		super.onDestroy();
	}

	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub

		super.onAttachedToWindow();
	}

	// public void setUnlock() {
	// vibrator.vibrate(500);
	// finish();
	// }

	@Override
	public void onUnlock() {
		// TODO Auto-generated method stub
		finish();
	}

	@Override
	public void onStateChange() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCancelUnlock() {
		// TODO Auto-generated method stub
		myPager.setCurrentItem(1);
	}

}
